package com.github.tangmonkmeat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Description:
 *
 * @author zwl
 * @version 1.0
 * @date 2021/2/26 上午11:04
 */
public class 四数之和 {

    public static void main(String[] args) {
        List<List<Integer>> lists = new 四数之和().fourSum(new int[]{2,2,2,2,2}, 8);
        System.out.println(lists);
    }

    // [1,1,0,-1,0,-2,2,2] 0
    public List<List<Integer>> fourSum(int[] nums, int target) {
        final int N = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        if (N < 4){
            return res;
        }
        Arrays.sort(nums);
        for (int i = 0; i <= N - 4; i++) {
            for (int j = N - 1; j >= i + 3; j--) {
                // 去重, 左右节点间距 >= N
                while (i > 0 && nums[i] == nums[i - 1] && i <= j -3){ i++; }
                while (j < N - 1 && nums[j] == nums[j + 1] && j >= i + 3){ j--; }

                int ii = i + 1;
                int jj = j - 1;
                while (ii < jj){
                    int x = nums[i] + nums[ii] + nums[j] + nums[jj] - target;
                    if (x == 0){
                        res.add(Arrays.asList(nums[i],nums[ii],nums[j],nums[jj]));
                        ii++;
                        jj--;
                        // 去重
                        while (ii < jj && nums[ii] == nums[ii - 1]){ ii++; }
                        while (jj > ii && nums[jj] == nums[jj + 1]){ jj--; }
                    }
                    else if(x < 0){
                        ii++;
                    }
                    else {
                        jj--;
                    }
                }
            }
        }
        return res;
    }

}
